﻿/*
 调用示例：await Request.GetRawBodyAsync();
作用：控件文件等后台程序，直接获取 HTTP 请求报文体中的 JSON 数据（不进行反序列化）：
 
 */

using System.Text;

public static class HttpRequestExtensions
{
    public static async Task<string> GetRawBodyAsync(
        this HttpRequest request,
        Encoding encoding = null)
    {
        if (!request.Body.CanRead)
        {
            return null;
        }

        if (encoding == null)
        {
            encoding = Encoding.UTF8;
        }

        // 确保可以多次读取
        if (request.Body.CanSeek)
        {
            request.Body.Position = 0;
        }
        else
        {
            request.EnableBuffering();
        }


        

        using var reader = new StreamReader(
            request.Body,
            encoding,
            detectEncodingFromByteOrderMarks: false,
            bufferSize: 1024,
            leaveOpen: true
        );

        var body = await reader.ReadToEndAsync();







        // 重置流位置
        if (request.Body.CanSeek)
        {
            request.Body.Position = 0;
        }

        return body;
    }
}